package model

import (
    "errors"
    "gorm.io/gorm"
    "yi-shou-backstage/util"
)

// 素材
type Image struct {
    ID int `gorm:"primaryKey;comment:图片id" json:"id,omitempty"`
    Url string `gorm:"type:varchar(256);not null;comment:图片url" json:"url,omitempty"`
    Collect bool `gorm:"type:bool;default:false;comment:是否被收藏" json:"collect"`
    Page int `gorm:"-" json:"page,omitempty"`
    PerPage int `gorm:"-" json:"per_page,omitempty"`
}

// 插入一条图片记录
func CreateImage(ImgObj Image) *Image {
    err := db.Create(&ImgObj).Error
    if err != nil {
        util.LogEntry.Errorf("Create Image error, error = %s \n", err)
    }
    return &ImgObj
}

// 通过主键查询
func GetImage(id int) *Image {
    var img Image
    err := db.First(&img, id).Error
    if errors.Is(err, gorm.ErrRecordNotFound) {
        util.LogEntry.Errorf("Image is not exist, image_id = %s \n", id)
        return nil
    }
    return &img
}

// 更新图片
func UpdateImage(id int, obj Image) *Image {
    img := Image{ID: id}
    err := db.Model(&img).Select("Collect").Updates(obj).Error
    if err != nil {
        util.LogEntry.Errorf("Update Image fialed, error = %s \n", err)
        return nil
    }
    return &img
}

// 用户图片列表
func ListUserImages(condition Image) (int64, []Image) {
    var images []Image
    var total int64
    offset := -1
    limit := -1
    if condition.Page == 1 {
        limit = condition.PerPage
    }else if condition.Page > 1 {
        offset = (condition.Page -1) * condition.PerPage
        limit = condition.PerPage
    }
    err := db.Where("collect = ?", condition.Collect).Find(&images).Count(&total).Error
    err = db.Where("collect = ?", condition.Collect).Offset(offset).Limit(limit).Find(&images).Error
    if err != nil {
        util.LogEntry.Errorf("List Images fialed, error = %s \n", err)
        return total, images
    }
    return total, images
}

// 删除图片
func DeleteImage(id int) *Image {
    img := Image{ID: id}
    err := db.Delete(&img).Error
    if err != nil {
        util.LogEntry.Errorf("Delete image fialed, error = %s \n", err)
        return nil
    }
    return &img
}